package com.binguo.service;

import com.alibaba.fastjson.JSONObject;
import com.binguo.common.util.ImageBase64Util;
import com.binguo.common.util.PriceUtil;
import com.binguo.common.util.UploadExcelService;
import com.binguo.helper.ImgHelper;
import com.binguo.model.mapper.CustomerMapper;
import com.binguo.model.model.*;
import com.binguo.model.repository.*;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author yuritian
 * @Title: YunPengCustomerService
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2020/3/2315:57
 */
@Service
public class YunPengCustomerService {
    private static final Logger logger = LoggerFactory.getLogger(YunPengCustomerService.class);


    @Autowired
    YpCardRepository ypCardRepository;

    @Autowired
    CustomerRechargeRepository customerRechargeRepository;

    @Autowired
    CustomerService customerService;

    @Resource
    CustomerMapper customerMapper;

    @Autowired
    PayCardRepository payCardRepository;

    @Autowired
    CustomerRepository customerRepository;

    @Autowired
    ShopService shopService;

    @Autowired
    CustomerExtendRepository customerExtendRepository;

    @Autowired
    FaceCopyRepository faceCopyRepository;

    @Autowired
    FaceRepository faceRepository;

    @Autowired
    ProductRepository productRepository;

    @Autowired
    BinguoOrderRepository binguoOrderRepository;

    @Resource
    CustomerGroupRepository customerGroupRepository;

    @Resource
    UploadExcelService uploadExcelServicel;

    @Resource
    FileUploadRepository fileUploadRepository;

    public static void main(String[] args)throws Exception {
        YunPengCustomerService yunPengCustomerService = new YunPengCustomerService();
        //System.out.println(yunPengCustomerService.getCardMenJinID("667E9949C8080400024B084F90E1071D"));
        yunPengCustomerService.addIntranetFace();

        String s = "'0000102065'\t'陈湘璐'\t";

        String t[] = s.split("'");

        System.out.println(t[1]);
    }

    public static void deleteProduct(Integer productId) {
        JSONObject param = new JSONObject();
        param.put("productId", productId);

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);
        DEFAULT_JSON_HEADER.add("Accept", MediaType.APPLICATION_JSON.toString());

        HttpEntity<String> entity = new HttpEntity<String>(param.toJSONString(), DEFAULT_JSON_HEADER);

        ResponseEntity<String> resp;
        resp = new RestTemplate().postForEntity("http://192.168.10.194/api/wxapp/product/delete", entity, String.class);
        logger.info(resp.getBody());

    }

    public void addTianShuiCustomer(){
        String filePath = "/Users/yuritian/Documents/天水街道/会员资料.xlsx";
        InputStream is;
        Workbook wb;
        try {
            is = new FileInputStream(filePath);
            wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            Row row;
            Cell cell;
            Integer rowNum = sheet.getPhysicalNumberOfRows();
            for (int i = 1;i < rowNum;i++){
                row = sheet.getRow(i);
                cell = row.getCell(0);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String cardNo = cell.getStringCellValue();
                cell = row.getCell(1);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String name = cell.getStringCellValue();
                cell = row.getCell(4);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String money = cell.getStringCellValue();
                cell = row.getCell(5);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String groupName = cell.getStringCellValue();
                cell = row.getCell(6);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String phone = cell.getStringCellValue();

                Customer customer = new Customer();
                customer.setPhone(phone);
                customer.setName(name);
                customerRepository.save(customer);
                CustomerExtend customerExtend = new CustomerExtend();
                customerExtend.setIsAudit(1);
                customerExtend.setCustomerId(customer.getId());
                customerExtend.setShopId(238);
                customerExtend.setUserStatus(1);
                if (groupName.equals("乐享卡")) {
                    customerExtend.setGroupId(408);
                    customerExtend.setGroupName("乐享卡");
                }else if (groupName.equals("乐优卡")) {
                    customerExtend.setGroupId(409);
                    customerExtend.setGroupName("乐优卡");
                }else if (groupName.equals("乐惠卡")) {
                    customerExtend.setGroupId(410);
                    customerExtend.setGroupName("乐惠卡");
                }
                customerExtendRepository.save(customerExtend);
                PayCard payCard = new PayCard();
                payCard.setCardno(cardNo);
                payCard.setAccountbalance(PriceUtil.getRealPrice(money));
                payCard.setDeleted(false);
                payCard.setShopid(238);
                payCard.setCustomerid(customer.getId());
                payCard.setName("天水街道老年食堂卡");
                payCard.setCardtype(new Byte("0"));
                payCard.setIsmaster(true);
                payCard.setIsnopasswordpay(true);
                payCard.setCreated(new Date());
                payCard.setUpdated(new Date());
                payCardRepository.save(payCard);
                YpCard ypCard = new YpCard();
                ypCard.setStatus(1);
                ypCard.setCardNo(cardNo);
                ypCard.setCardId(cardNo);
                ypCard.setCreateTime(new Date());
                ypCard.setBindingTime(new Date());
                ypCard.setShopId(238);
                ypCardRepository.save(ypCard);
            }

        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addCustomer(){
        String filePath = "/Users/yuritian/Documents/国网安徽营销服务中心/国网安徽营销服务中心上传.xlsx";
        InputStream is;
        Workbook wb;
        Integer index = 1;
        Integer shopId = 268;
        Shop shop = shopService.shopRepository.findById(shopId);
        try {
            is = new FileInputStream(filePath);
            wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            Row row;
            Cell cell;
            Integer rowNum = sheet.getPhysicalNumberOfRows();
            for (int i = 0;i < rowNum;i++){
                row = sheet.getRow(i);
                cell = row.getCell(0);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String groupName = cell.getStringCellValue();
                cell = row.getCell(1);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String name = cell.getStringCellValue();
                cell = row.getCell(2);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String phone = cell.getStringCellValue();
                cell = row.getCell(3);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String cardId = cell.getStringCellValue();

                if (!StringUtils.hasText(phone)){
                   phone = shopId + "--" + index;
                   index++;
                }

                Customer customer = new Customer();
                customer.setPhone(phone);
                customer.setName(name);
                customerRepository.save(customer);
                CustomerExtend customerExtend = new CustomerExtend();
                customerExtend.setIsAudit(1);
                customerExtend.setCustomerId(customer.getId());
                customerExtend.setShopId(shopId);
                customerExtend.setUserStatus(1);
                customerExtend.setGroupName(groupName);
                Condition condition = new Condition(CustomerGroup.class);
                condition.or().andEqualTo("groupName",groupName)
                        .andEqualTo("shopId",shopId);
                List<CustomerGroup> groupList = customerGroupRepository.findByCondition(condition);
                if (groupList != null && groupList.size()>0){
                    customerExtend.setGroupId(groupList.get(0).getId());
                }else {
                    CustomerGroup customerGroup = new CustomerGroup();
                    customerGroup.setShopId(shopId);
                    customerGroup.setDeleted(0);
                    customerGroup.setStatus(1);
                    customerGroup.setGroupName(groupName);
                    customerGroupRepository.save(customerGroup);
                    customerExtend.setGroupId(customerGroup.getId());
                }
                customerExtendRepository.save(customerExtend);

                PayCard payCard = new PayCard();
                payCard.setDeleted(false);
                payCard.setShopid(shopId);
                payCard.setCustomerid(customer.getId());
                payCard.setName(shop.getName());
                payCard.setCardtype(new Byte("0"));
                payCard.setIsmaster(true);
                payCard.setIsnopasswordpay(true);
                payCard.setCreated(new Date());
                payCard.setUpdated(new Date());
                payCardRepository.save(payCard);
                payCard.setCardno(payCard.getId().toString());
                payCardRepository.update(payCard);
                YpCard ypCard = new YpCard();
                ypCard.setStatus(1);
                ypCard.setCardNo(payCard.getCardno());
                ypCard.setCardId(cardId);
                ypCard.setCardMenjinId(getCardMenJinID(cardId));
                ypCard.setCreateTime(new Date());
                ypCard.setBindingTime(new Date());
                ypCard.setShopId(shopId);
                ypCardRepository.save(ypCard);

            }

        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void bindingYunPengCard() {
        String filePath = "/Users/yuritian/Documents/常德/20200320常德财富中心门禁卡.xlsx";
        InputStream is;
        Workbook wb;
        Map<String, Integer> phoneMap = new HashMap<>();
        try {
            is = new FileInputStream(filePath);
            wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            Row row;
            Integer rowNum = sheet.getPhysicalNumberOfRows();
            for (int i = 2; i < rowNum; i++) {
                row = sheet.getRow(i);
                row.getCell(1).setCellType(XSSFCell.CELL_TYPE_STRING);
                String cardNo = row.getCell(1).getStringCellValue();
                row.getCell(4).setCellType(XSSFCell.CELL_TYPE_STRING);
                String cardId = row.getCell(4).getStringCellValue();
                System.out.println("cardNo:" + cardNo + "cardId:" + cardId);
                if (StringUtils.hasText(cardNo) && StringUtils.hasText(cardId)) {
                    Condition condition = new Condition(YpCard.class);
                    condition.or().andEqualTo("cardId", cardId)
                            .andEqualTo("shopId", 215);
                    List<YpCard> ypCardList = ypCardRepository.findByCondition(condition);
                    if (ypCardList == null || ypCardList.size() == 0) {
                        YpCard ypCard = new YpCard();
                        ypCard.setStatus(1);
                        ypCard.setCardNo(cardNo);
                        ypCard.setCardId(cardId);
                        ypCard.setCreateTime(new Date());
                        ypCard.setBindingTime(new Date());
                        ypCard.setShopId(215);
                        ypCardRepository.save(ypCard);
                    }
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addProduct() {
        String filePath = "/Users/yuritian/Documents/兰溪电厂/菜单.xls";
        InputStream is;
        Workbook wb;
        try {
            is = new FileInputStream(filePath);
            wb = new HSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            Row row;
            Integer rowNum = sheet.getPhysicalNumberOfRows();
            for (int i = 1; i < rowNum; i++) {
                row = sheet.getRow(i);
                row.getCell(1).setCellType(XSSFCell.CELL_TYPE_STRING);
                String name = row.getCell(1).getStringCellValue();
                row.getCell(4).setCellType(XSSFCell.CELL_TYPE_STRING);
                String price = row.getCell(4).getStringCellValue();
                System.out.println("name:" + name + "   price:" + price);
                Product product = new Product();
                product.setName(name);
                product.setStatus(new Byte("1"));
                product.setShopid(221);
                product.setCreated(new Date());
                product.setPrice(PriceUtil.getRealPrice(price));
                product.setDeleted(false);
                product.setMinorcategoryid(343);
                product.setVipprice(PriceUtil.getRealPrice(price));
                product.setProductType(1);
                product.setStoreid(241);
                productRepository.save(product);
                product.setSearchcode(product.getId().toString());
                productRepository.update(product);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Map<String, String> getUserId() throws Exception{
        String filepath = "/Users/jay/IdeaProjects/binguo/service/target/无标题.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filepath));

        String line = bufferedReader.readLine().trim();

        Map<String, String> map = new HashMap<>();
        while (StringUtils.hasText(line)) {
            String temp[] = line.split(",");

            String customerId = temp[0].replaceAll("'", "");

            String cardNo = temp[1];

            cardNo = cardNo.split("'")[1];

            System.out.println("cardNo=" + cardNo + ",customer=" + customerId);
            map.put(cardNo, customerId);
            line = bufferedReader.readLine();
        }

        return map;
    }
    public void addIntranetFace() throws Exception{

        Map<String, String> map = getUserId();
        String filePath = "/Users/jay/IdeaProjects/binguo/service/target/副本照片对照.xlsx";
        InputStream is;
        Workbook wb;
        try {
            is = new FileInputStream(filePath);
            wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            sheet = withoutRowEmpty(sheet);
            Row row;
            Cell cell;
            Integer rowNum = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < rowNum; i++) {
                row = sheet.getRow(i);
                cell = row.getCell(0);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String phone = cell.getStringCellValue();
                cell = row.getCell(1);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String name = cell.getStringCellValue();
                cell = row.getCell(2);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String picPath = cell.getStringCellValue();
//                Customer customer = customerService.getCustomerByPhone(phone);
                /*Customer customer = new Customer();
                customer.setPhone(phone);
                customer.setName(name);
                customerRepository.save(customer);
                CustomerExtend customerExtend = new CustomerExtend();
                customerExtend.setIsAudit(1);
                customerExtend.setCustomerId(customer.getId());
                customerExtend.setShopId(250);
                customerExtend.setUserStatus(1);
                customerExtend.setGroupId(0);
                customerExtend.setGroupName("普通会员");
                customerExtendRepository.save(customerExtend);
                PayCard payCard = new PayCard();
                payCard.setCardno(phone);
                payCard.setDeleted(false);
                payCard.setShopid(250);
                payCard.setCustomerid(customer.getId());
                payCard.setName("民生银行卡");
                payCard.setCardtype(new Byte("0"));
                payCard.setIsmaster(true);
                payCard.setIsnopasswordpay(true);
                payCard.setCreated(new Date());
                payCard.setUpdated(new Date());
                payCardRepository.save(payCard);*/

                if (StringUtils.hasText(picPath)) {

                    HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
                    MediaType jsontype = MediaType.APPLICATION_JSON;
                    DEFAULT_JSON_HEADER.setContentType(jsontype);
                    DEFAULT_JSON_HEADER.add("Accept", MediaType.APPLICATION_JSON.toString());


                    String imgUrl = "http://195.30.8.55/images/faces/temp/"+picPath;

                    JSONObject param = new JSONObject();
                    param.put("shopId", 250);
                    param.put("customerId", map.get(phone));
                    param.put("faceUrl", imgUrl);
                    logger.info("postParam :" + param.toJSONString());
//                    HttpEntity<String> entity = new HttpEntity<String>(param.toJSONString(), DEFAULT_JSON_HEADER);
//                    ResponseEntity<String> resp = new RestTemplate().postForEntity("http://195.30.8.55/api/wxapp/face/cmsCreate", entity, String.class);
//                    logger.info(resp.getBody());
                }

//                try {0000176244 .JPG
////                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addTestFace() {
        List<Face> faceCopyList = faceRepository.findAll();
        Long phone = 30000000000L;
        Integer i = 1;
        for (Face faceCopy : faceCopyList) {
            Customer customer = new Customer();
            customer.setPhone(phone.toString());
            customer.setName("194测试" + i);
            customerRepository.save(customer);
            CustomerExtend customerExtend = new CustomerExtend();
            customerExtend.setIsAudit(1);
            customerExtend.setCustomerId(customer.getId());
            customerExtend.setShopId(217);
            customerExtend.setUserStatus(1);
            customerExtend.setGroupId(0);
            customerExtend.setGroupName("普通会员");
            customerExtendRepository.save(customerExtend);
            PayCard payCard = new PayCard();
            payCard.setCardno(phone.toString());
            payCard.setBzAccountbalance(100000L);
            payCard.setDeleted(false);
            payCard.setShopid(217);
            payCard.setCustomerid(customer.getId());
            payCard.setName("宁波鑫食餐饮管理服务有限公司卡");
            payCard.setCardtype(new Byte("0"));
            payCard.setIsmaster(true);
            payCard.setIsnopasswordpay(true);
            payCard.setCreated(new Date());
            payCard.setUpdated(new Date());
            payCardRepository.save(payCard);
            JSONObject param = new JSONObject();
            param.put("shopId", 217);
            param.put("customerId", customer.getId());
            param.put("faceUrl", faceCopy.getFaceurl());

            HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
            MediaType jsontype = MediaType.APPLICATION_JSON;
            DEFAULT_JSON_HEADER.setContentType(jsontype);
            DEFAULT_JSON_HEADER.add("Accept", MediaType.APPLICATION_JSON.toString());

            HttpEntity<String> entity = new HttpEntity<String>(param.toJSONString(), DEFAULT_JSON_HEADER);

            ResponseEntity<String> resp;
            resp = new RestTemplate().postForEntity("http://192.168.10.194/api/wxapp/face/cmsCreate", entity, String.class);
            logger.info(resp.getBody());
            phone++;
            i++;
        }
    }

    public void addProductList() {

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);
        DEFAULT_JSON_HEADER.add("Accept", MediaType.APPLICATION_JSON.toString());

        String path = "/Users/yuritian/Documents/菜品图片"; // 路径
        File f = new File(path);

        File[] fa = f.listFiles();
        for (int i = 0; i < fa.length; i++) {
            logger.info(i + "");
            File fs = fa[i];
            JSONObject productParam = new JSONObject();
            if (!isInteger(fs.getName())) {
                continue;
            }
            productParam.put("productName", "217" + fs.getName());
            productParam.put("productPrice", "0.01");
            productParam.put("productCategoryID", 3);
            productParam.put("shopId", "217");
            productParam.put("branchId", "1");
            HttpEntity<String> entity = new HttpEntity<String>(productParam.toJSONString(), DEFAULT_JSON_HEADER);

            ResponseEntity<String> resp = new RestTemplate().postForEntity("http://192.168.10.194/api/wxapp/product/create", entity, String.class);


            String createResult = resp.getBody();
            JSONObject json = JSONObject.parseObject(createResult);

            Integer productId = json.getInteger("data");

            File[] fp = fs.listFiles();
            for (int j = 0; j < fp.length; j++) {
                File productPic = fp[j];
                String extName = productPic.getName().substring(productPic.getName().lastIndexOf(".") + 1);
                String base64 = null;
                FileInputStream fin = null;
                try {
                    fin = new FileInputStream(productPic);
                    byte[] buff = new byte[fin.available()];
                    fin.read(buff);
                    base64 = Base64.getEncoder().encodeToString(buff);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject param = new JSONObject();
                param.put("shopId", 217);
                param.put("type", 1);
                param.put("img64", base64);
                param.put("suffix", extName);

                entity = new HttpEntity<String>(param.toJSONString(), DEFAULT_JSON_HEADER);

                resp = new RestTemplate().postForEntity("http://192.168.10.194/api/local/cos/uploadImage", entity, String.class);
                //ResponseEntity<String> resp = new RestTemplate().postForEntity( "http://192.168.10.27/api/local/cos/uploadImage", entity, String.class);


                String imgResult = resp.getBody();
                JSONObject imgResultJson = JSONObject.parseObject(imgResult);
                Integer code = imgResultJson.getInteger("code");
                String imgUrl;
                if (code.equals(200)) {
                    imgUrl = imgResultJson.getString("data");
                } else {
                    logger.info("上传图片失败");
                    continue;
                }
                param = new JSONObject();
                param.put("productId", productId.toString());
                param.put("productUrl", imgUrl);

                entity = new HttpEntity<String>(param.toJSONString(), DEFAULT_JSON_HEADER);

                resp = new RestTemplate().postForEntity("http://192.168.10.194/api/wxapp/productimg/create", entity, String.class);
                logger.info(productId + ":  " + resp.getBody());
            }
        }
    }

    public void addLanxiFace() {

        Integer shopId = 240;

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);
        DEFAULT_JSON_HEADER.add("Accept", MediaType.APPLICATION_JSON.toString());

        // 路径
        String path = "/Users/yuritian/Downloads/txl";
        File f = new File(path);

        File[] fa = f.listFiles();
        for (int i = 0; i < fa.length; i++) {
            logger.info(i + "");
            File productPic = fa[i];
            String extName = productPic.getName().substring(productPic.getName().lastIndexOf(".") + 1);
            String name = productPic.getName().substring(0, productPic.getName().lastIndexOf("."));
            if (!extName.equals("JPG")) {
                continue;
            }

            try {
                BufferedImage bufferedImage = ImageIO.read(productPic);
                // create a blank, RGB, same width and height, and a white
                // background
                BufferedImage newBufferedImage = new BufferedImage(
                        bufferedImage.getWidth(), bufferedImage.getHeight(),
                        BufferedImage.TYPE_INT_RGB);
                // TYPE_INT_RGB:创建一个RBG图像，24位深度，成功将32位图转化成24位
                newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0,
                        Color.WHITE, null);
                // write to jpeg file
                ImageIO.write(newBufferedImage, "jpg", productPic);
                byte[] bytes = FileUtils.readFileToByteArray(productPic);
                // 图片小于500kb
                bytes = ImageBase64Util.compressPicForScale(bytes, 500, "x");
                FileUtils.writeByteArrayToFile(productPic, bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }

            String base64 = null;
            FileInputStream fin;
            try {
                fin = new FileInputStream(productPic);
                byte[] buff = new byte[fin.available()];
                fin.read(buff);
                base64 = Base64.getEncoder().encodeToString(buff);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject param = new JSONObject();
            param.put("shopId", shopId);
            param.put("type", 1);
            param.put("img64", base64);
            param.put("suffix", extName);

            HttpEntity<String> entity = new HttpEntity<String>(param.toJSONString(), DEFAULT_JSON_HEADER);

            ResponseEntity<String> resp = new RestTemplate().postForEntity("http://123.206.224.209:8777/api/local/cos/uploadImage", entity, String.class);
            //ResponseEntity<String> resp = new RestTemplate().postForEntity( "http://192.168.10.27/api/local/cos/uploadImage", entity, String.class);


            String imgResult = resp.getBody();
            JSONObject imgResultJson = JSONObject.parseObject(imgResult);
            Integer code = imgResultJson.getInteger("code");
            String imgUrl;
            if (code.equals(200)) {
                imgUrl = imgResultJson.getString("data");
            } else {
                logger.info("上传图片失败");
                continue;
            }

            String phone = name.split("_")[0].trim();
            String customerName = name.split("_")[1].trim();
            Customer customer = customerService.getCustomerByPhone(phone);
            if(customer == null) {
                customer = new Customer();
                customer.setPhone(phone);
                customer.setName(customerName);
                customerRepository.save(customer);
            }
            CustomerExtend customerExtend = new CustomerExtend();
            customerExtend.setIsAudit(1);
            customerExtend.setCustomerId(customer.getId());
            customerExtend.setShopId(shopId);
            customerExtend.setUserStatus(1);
            customerExtend.setGroupId(406);
            customerExtend.setGroupName("行业拓展部");
            customerExtendRepository.save(customerExtend);
            PayCard payCard = new PayCard();
            payCard.setDeleted(false);
            payCard.setShopid(shopId);
            payCard.setCustomerid(customer.getId());
            payCard.setName("中国铁塔金华分公司卡");
            payCard.setCardtype(new Byte("0"));
            payCard.setIsmaster(true);
            payCard.setIsnopasswordpay(true);
            payCard.setCreated(new Date());
            payCard.setUpdated(new Date());
            payCardRepository.save(payCard);
            payCard.setCardno(payCard.getId().toString());
            payCardRepository.update(payCard);

            param = new JSONObject();
            param.put("shopId", shopId);
            param.put("customerId", customer.getId());
            param.put("faceUrl", imgUrl);

            entity = new HttpEntity<String>(param.toJSONString(), DEFAULT_JSON_HEADER);

            resp = new RestTemplate().postForEntity("https://binguoai.com/api/wxapp/face/cmsCreate", entity, String.class);
            logger.info(resp.getBody());
        }
    }

    public void exportBalance() {
        String filePath = "/Users/yuritian/Documents/蚌埠反馈/蚌埠12月份补助 转存余额.xlsx";
        InputStream is;
        Workbook wb;
        try {
            is = new FileInputStream(filePath);
            wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            Row row;
            Cell cell;
            Integer rowNum = sheet.getPhysicalNumberOfRows();
            Long sumRealBz = 0L;
            Long sumRealYkt = 0L;
            for (int i = 1; i < rowNum; i++) {
                row = sheet.getRow(i);
                row.getCell(0).setCellType(XSSFCell.CELL_TYPE_STRING);
                String customerId = row.getCell(0).getStringCellValue();
                row.getCell(1).setCellType(XSSFCell.CELL_TYPE_STRING);
                String bzBalance = row.getCell(1).getStringCellValue();
                row.getCell(2).setCellType(XSSFCell.CELL_TYPE_STRING);
                String yktBalance = row.getCell(2).getStringCellValue();
                Long realBzBalance = Long.parseLong(bzBalance);
                Long realYktBalance = Long.parseLong(yktBalance);
                row.getCell(1).setCellValue(PriceUtil.changeF2Y(realBzBalance) + "元");
                sumRealBz += realBzBalance;
                row.getCell(2).setCellValue(PriceUtil.changeF2Y(realYktBalance) + "元");
                sumRealYkt += realYktBalance;
            }
            row = sheet.createRow(rowNum);
            cell = row.createCell(1);
            cell.setCellValue(PriceUtil.changeF2Y(sumRealBz) + "元");
            cell = row.createCell(2);
            cell.setCellValue(PriceUtil.changeF2Y(sumRealYkt) + "元");

            OutputStream os;

            //根据路径创建输出流
            //如果是在controller里可以使用reponse.getOutputStream()方法获取输出流
            os = new FileOutputStream(filePath);
            wb.write(os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addYpCard(){
        String filePath = "/Users/yuritian/Documents/悦馨餐饮/悦馨餐饮就餐卡.xlsx";
        InputStream is;
        Workbook wb;
        try {
            is = new FileInputStream(filePath);
            wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            Row row;
            Cell cell;
            Integer rowNum = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < rowNum; i++) {
                row = sheet.getRow(i);
                cell = row.getCell(1);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String cardId = cell.getStringCellValue();
                cell = row.getCell(0);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String cardNo = cell.getStringCellValue();
                cardNo = cardNo.substring(3);
                YpCard ypCard = new YpCard();
                ypCard.setCardNo(cardNo);
                ypCard.setCardId(cardId);
                ypCard.setCardMenjinId(getCardMenJinID(cardId));
                ypCard.setShopId(263);
                ypCard.setStatus(0);
                ypCard.setCreateTime(new Date());
                ypCardRepository.save(ypCard);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getShopCustomerIdList(Integer shopId) {
        List<Integer> customerIdList = customerMapper.shopCustomerIdList(shopId);

        String idList = "";

        for (int i = 0; i < customerIdList.size() - 1; i++) {
            idList += customerIdList.get(i) + ",";
        }
        idList += customerIdList.get(customerIdList.size() - 1);
        System.out.println(idList);
    }

    private Integer getPrice(String price) {

        BigDecimal oldPrice = new BigDecimal(price);

        BigDecimal a = new BigDecimal("100");

        return oldPrice.multiply(a).intValue();
    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public String getCardMenJinID(String cardID){
        String card_id = cardID;
        card_id = card_id.substring(0, 8);
        System.out.println(card_id);
        String card_id_1 = card_id.substring(0, 2);
        String card_id_2 = card_id.substring(2, 4);
        String card_id_3 = card_id.substring(4, 6);
        String card_id_4 = card_id.substring(6, 8);
        String newCard_id = card_id_4 + card_id_3 + card_id_2 + card_id_1;
        System.out.println(newCard_id);
        Long valueTen2 = Long.parseLong(newCard_id, 16);
        return valueTen2.toString();
    }

    public Sheet withoutRowEmpty(Sheet sheet){
        boolean flag;
        for (int i = 1; i <= sheet.getLastRowNum();) {
            Row r = sheet.getRow(i);
            if(r == null){
                // 如果是空行（即没有任何数据、格式），直接把它以下的数据往上移动
                sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
                continue;
            }
            flag = false;
            for(Cell c:r){
                if(c.getCellType() != Cell.CELL_TYPE_BLANK){
                    flag = true;
                    break;
                }
            }
            if(flag){
                i++;
                continue;
            }
            else{//如果是空白行（即可能没有数据，但是有一定格式）
                if(i == sheet.getLastRowNum()) {
                    //如果到了最后一行，直接将那一行remove掉
                    sheet.removeRow(r);
                } else{
                    //如果还没到最后一行，则数据往上移一行
                    sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
                }
            }
        }
        System.out.println("总行数："+(sheet.getLastRowNum()+1));
        return sheet;
    }


    public void updateFaceIMG(){
        String path = "/Users/yuritian/Downloads/txl";
        File f = new File(path);

        File[] fa = f.listFiles();
        for (int i = 0; i < fa.length; i++) {
            logger.info(i + "");
            File productPic = fa[i];
            String extName = productPic.getName().substring(productPic.getName().lastIndexOf(".") + 1);
            if (!extName.equals("JPG")) {
                continue;
            }

            try {
                BufferedImage bufferedImage = ImageIO.read(productPic);
                // create a blank, RGB, same width and height, and a white
                // background
                BufferedImage newBufferedImage = new BufferedImage(
                        bufferedImage.getWidth(), bufferedImage.getHeight(),
                        BufferedImage.TYPE_INT_RGB);
                // TYPE_INT_RGB:创建一个RBG图像，24位深度，成功将32位图转化成24位
                newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0,
                        Color.WHITE, null);
                // write to jpeg file
                ImageIO.write(newBufferedImage, "jpg", productPic);
                byte[] bytes = FileUtils.readFileToByteArray(productPic);
                // 图片小于500kb
                bytes = ImageBase64Util.compressPicForScale(bytes, 3072, "x");
                FileUtils.writeByteArrayToFile(productPic, bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
